package com.woniuxy.commons.filter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.commons.exception.LoginException;
import com.woniuxy.commons.exception.UserException;
import com.woniuxy.commons.exception.code.UserExceptionCode;
import com.woniuxy.dao.model.AccountInfo;
import com.woniuxy.dao.model.CustomerInfo;
import com.woniuxy.dao.model.StoreInfo;
import com.woniuxy.service.AccountInfoService;
import com.woniuxy.service.CustomerInfoService;
import com.woniuxy.service.StoreInfoService;
import com.woniuxy.service.dto.UserDetailsDto;
import lombok.SneakyThrows;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class    PhoneLoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "phone";
    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "code";
    private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher("/phoneLogin", "POST");
    private String phoneParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
    private String codeParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
    private boolean postOnly = true;

    private AccountInfoService accountInfoService;

    private StoreInfoService storeInfoService;

    private CustomerInfoService customerInfoService;

    private StringRedisTemplate srt;

    public PhoneLoginAuthenticationFilter(AccountInfoService accountInfoService,
                                          StoreInfoService storeInfoService,
                                          CustomerInfoService customerInfoService,
                                          StringRedisTemplate srt) {
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
        this.accountInfoService = accountInfoService;
        this.storeInfoService = storeInfoService;
        this.customerInfoService = customerInfoService;
        this.srt = srt;
    }


    public PhoneLoginAuthenticationFilter() {
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
    }

    public PhoneLoginAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER, authenticationManager);
    }

    @SneakyThrows
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (this.postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            String phone = this.obtainPhone(request);
            phone = phone != null ? phone : "";
            phone = phone.trim();
            String code = this.obtainCode(request);
            code = code != null ? code : "";
            code = code.trim();

            //通过电话查询用户
            System.out.println(phone);

            AccountInfo accountInfo = accountInfoService.getOne(new QueryWrapper<AccountInfo>().eq("accountPhone", phone));

            if(accountInfo != null) {

                String phoneCode = srt.opsForValue().get("login:phone:code" + phone);

                if(phoneCode == null || phoneCode.trim().equals("")) throw new UserException(UserExceptionCode.USER_CODE_NOT_EXITS);

                if(!phoneCode.equals(code)) throw new UserException(UserExceptionCode.USER_CODE_WRONG);

                UserDetailsDto ud = new UserDetailsDto();
                ud.setAccountId(accountInfo.getAccountId());
                ud.setUsername(accountInfo.getAccountName());
                ud.setPassword(accountInfo.getAccountPassword());
                if (accountInfo.getAccountType() == 1) {
                    StoreInfo storeInfo = storeInfoService.getOne(new QueryWrapper<StoreInfo>().eq("accountId", accountInfo.getAccountId()));
                    ud.setId(storeInfo.getId());
                    ud.setPhone(storeInfo.getPhone());
                } else if (accountInfo.getAccountType() == 2) {
                    CustomerInfo customerInfo = customerInfoService.getOne(new QueryWrapper<CustomerInfo>().eq("accountId", accountInfo.getAccountId()));
                    ud.setId(customerInfo.getId());
                    ud.setPhone(customerInfo.getPhone());
                }
                PhoneCodeAuthenticationToken token =
                        new PhoneCodeAuthenticationToken(ud, null);
                setDetails(request, token);
                return token;
            }
            throw new LoginException("该账号不存在");
        }
    }



    @Nullable
    protected String obtainCode(HttpServletRequest request) {
        return request.getParameter(this.codeParameter);
    }

    @Nullable
    protected String obtainPhone(HttpServletRequest request) {
        return request.getParameter(this.phoneParameter);
    }

    protected void setDetails(HttpServletRequest request, PhoneCodeAuthenticationToken authRequest) {
        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }



    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }

    public final String getPhoneParameter() {
        return this.phoneParameter;
    }

    public final String getCodeParameter() {
        return this.codeParameter;
    }
}
